/*

  The MIT License

  Copyright (c) 2008 - 2010. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.display
{

import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import flash.utils.Endian;

//-------------------------------------
//  Excluded APIs
//-------------------------------------

[Exclude(name="contentLoaderInfo", kind="property")]

//-------------------------------------
//  Events
//-------------------------------------

/**
 * @copy			flash.display.LoaderInfo#complete
 * @eventType		flash.events.Event.COMPLETE
 * 
 */
[Event(name="complete", type="flash.events.Event")]

/**
 * @copy			flash.display.LoaderInfo#progress
 * @eventType		flash.events.ProgressEvent.PROGRESS
 * 
 */
[Event(name="progress", type="flash.events.ProgressEvent")]

/**
 * @copy			flash.display.LoaderInfo#ioError
 * @eventType		flash.events.IOErrorEvent.IO_ERROR
 * 
 */
[Event(name="ioError", type="flash.events.IOErrorEvent")]

/**
 * @copy			flash.display.LoaderInfo#securityError
 * @eventType		flash.events.SecurityErrorEvent.SECURITY_ERROR
 * 
 */
[Event(name="securityError", type="flash.events.SecurityErrorEvent")]

/**
 * @copy			flash.display.LoaderInfo#httpStatus
 * @eventType		flash.events.HTTPStatusEvent.HTTP_STATUS
 * 
 */
[Event(name="httpStatus", type="flash.events.HTTPStatusEvent")]

/**
 * 
 * 
 * @author				Dimarik
 * @version				1.2
 * @langversion			3.0
 * @playerversion		9.0
 * 
 */
public final class GIFLoader extends Loader {

	//-------------------------------------------------------------------------
	//
	//   Class methods
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function GIFLoader (
								qname:			QName = null,
								smooth:			Boolean = false, 
								useDelays:		Boolean = true, 
								stageFrameRate:	uint = 20
	) {
		super();
		this._qname		= qname;
		this._smooth	= smooth;
		this._useDelays	= useDelays;
		this._stageFPS	= stageFrameRate & 0xFF;

		super.contentLoaderInfo.addEventListener(Event.COMPLETE,	this.handler_complete,			false,	int.MAX_VALUE);
		super.contentLoaderInfo.addEventListener(Event.COMPLETE,	this.handler_resourceComplete,	false,	int.MAX_VALUE - 1);
	}

	//-------------------------------------------------------------------------
	//
	//   Overridden properties: Loader
	//
	//-------------------------------------------------------------------------

	//---------------------------------
	//  content
	//---------------------------------
	/**
	 * @private 
	 */
	private var _content:			DisplayObject;

	/**
	 * @inheritDoc
	 */
	public override function get content():DisplayObject {

		if ( !this._content ) {
			if ( this._class )
				this._content = new this._class() as DisplayObject;
		}

		return this._content;
	}

	//---------------------------------
	//  contentLoaderInfo. deprecated
	//---------------------------------
	[Deprecated(message="Class does not implement this property")]
	/**
	 * @private
	 */
	public override function get contentLoaderInfo():LoaderInfo {
		throw new IllegalOperationError('The class does not implement this property.');
	}

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	/**
	 * @copy LoaderInfo#bytesLoaded
	 */
	public function get bytesLoaded():uint {
		return super.contentLoaderInfo.bytesLoaded;
	}

	/**
	 * @copy LoaderInfo#bytesTotal
	 */
	public function get bytesTotal():uint {
		return super.contentLoaderInfo.bytesTotal;
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private var _init:			Boolean = true;

	/**
	 * @private 
	 */
	private var _qname:			QName;

	/**
	 * @private 
	 */
	private var _smooth:		Boolean;

	/**
	 * @private 
	 */
	private var _useDelays:		Boolean;

	/**
	 * @private 
	 */
	private var _stageFPS:		uint;

	/**
	 * @private 
	 */
	private var _context:		LoaderContext;

	/**
	 * @private 
	 */
	private var _class:			Class;

	//-------------------------------------------------------------------------
	//
	//   Overridden methods: Loader
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc
	 *  
	 * @param request
	 * @param context
	 * 
	 */
	public override function load(request:URLRequest, context:LoaderContext = null):void {
		this._context = context;
		this._init = true;
		this.configureListeners(super.contentLoaderInfo.addEventListener);
		super.load(request);
	}

	/**
	 * @inheritDoc
	 */
	public override function unload():void {
		this._content = null;
		this._class = null;
		this.configureListeners(super.contentLoaderInfo.removeEventListener);
		super.unload();
	}

	/**
	 * @inheritDoc
	 */
	CONFIG::fp10
	public override function unloadAndStop(gc:Boolean = true):void {
		this._content = null;
		this._class = null;
		this.configureListeners(super.contentLoaderInfo.removeEventListener);
		super.unloadAndStop(gc);
	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------
	/**
	 * @private
	 */
	private function configureListeners(method:Function):void {
		method.call(null, IOErrorEvent.IO_ERROR,				super.dispatchEvent);
		method.call(null, SecurityErrorEvent.SECURITY_ERROR,	super.dispatchEvent);
		method.call(null, ProgressEvent.PROGRESS,				super.dispatchEvent);
		method.call(null, HTTPStatusEvent.HTTP_STATUS,			super.dispatchEvent);
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------

	/**
	 * 
	 * @param event
	 * 
	 */
	private function handler_complete(event:Event):void {
		if ( !this._init )
			return;

		this._init = false;
		event.stopImmediatePropagation();

		var li:LoaderInfo = event.target as LoaderInfo;
		this.configureListeners(li.removeEventListener);

		super.dispatchEvent( new Event(Event.INIT) );

		if ( !this._qname ) {
			var url:String = 'ru.goodcore.resource';
			var localName:String = '';

			var regExp:RegExp = /.*?\/{2,3}(?P<url>\/?.*)\/(?P<localName>.*)/i;
			var o:Object = regExp.exec(li.url);

			if (o && o.url) {
				o.url = unescape(o.url);
				o.url = (o.url as String).replace(/\//ig, '.');
				url += '.' + o.url;
			}

			if (o && o.localName) {
				o.localName = unescape(o.localName);
				o.localName = (o.localName as String).replace(/\./ig, '_');
				localName = o.localName;
			} else {
				localName = int(Math.random() * int.MAX_VALUE).toString(33).toUpperCase();
			}

			this._qname = new QName(url, localName);
		}

		var ba:ByteArray = li.bytes;
		ba.endian = Endian.LITTLE_ENDIAN;

		// Читаем до 0xBF [17]h (DefineBitsJPEG4)
		while ( ba.readUnsignedByte() != 0xBF ) void;
		ba.position += 7;
		var len:uint = ba.readUnsignedInt(); // Размер гифки в байтах		
		ba.position += 2; // skip DeblockParam
		ba.readBytes(ba, 0, len);
		ba.position = 0;

		var swf:SWFGIFMovieClip = new SWFGIFMovieClip(ba, this._qname, this._smooth, this._useDelays ? this._stageFPS : 0);
		super.loadBytes( swf, this._context );
	}

	/**
	 * @private
	 */
	private function handler_resourceComplete(event:Event):void {
		this._class = super.contentLoaderInfo.applicationDomain.getDefinition( this._qname.toString() ) as Class;
		super.dispatchEvent(event);
	}

}
}
